package zcw.com.lib_leet_code;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * Created by 朱城委 on 2021/7/26.<br><br>
 *
 * 有效的括号
 */
public class Topic20 {

    public static void main(String[] args) {
        Topic20 instance = new Topic20();

        System.out.println(instance.isValid("()"));
        System.out.println(instance.isValid("()[]{}"));
        System.out.println(instance.isValid("(]"));
        System.out.println(instance.isValid("([)]"));
    }

    public boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();

        for(char ch : s.toCharArray()) {
            switch (ch) {
                case '(':
                case '[':
                case '{':
                    stack.push(ch);
                    break;

                case ')':
                    if(stack.isEmpty() || stack.peek() != '(') {
                        return false;
                    }
                    stack.pop();
                    break;

                case ']':
                    if(stack.isEmpty() || stack.peek() != '[') {
                        return false;
                    }
                    stack.pop();
                    break;

                case '}':
                    if(stack.isEmpty() || stack.peek() != '{') {
                        return false;
                    }
                    stack.pop();
                    break;
            }
        }

        return stack.size() == 0;
    }
}
